package com.example.demo.hadoop.hdfs.controller;

import com.example.demo.hadoop.utils.HdfsUtils;
import org.apache.hadoop.fs.BlockLocation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("hello")
public class HdfsController {
    @RequestMapping({"/index", "/", ""})
    public String index() {
        return "this is index ...";
    }


    @Autowired
    HdfsUtils hdfsUtils;

    @RequestMapping("mkdir")
    @ResponseBody
    public boolean mkdir(String path) throws Exception {
        return hdfsUtils.mkdir(path);
    }

    @RequestMapping("pathInfos")
    @ResponseBody
    public List<Map<String, Object>> pathInfos(@RequestParam("path") String path) throws Exception {
        if (StringUtils.isEmpty(path)) {
            path = "/";
        }
        return hdfsUtils.readPathInfo(path);
    }

    @RequestMapping("addFile")
    @ResponseBody
    public String addFile(String path, MultipartFile file) throws Exception {
        hdfsUtils.createFile(path, file);
        return "success";
    }

    @RequestMapping("readFile")
    @ResponseBody
    public String readFile(String path) throws Exception {
        return hdfsUtils.readFile(path);
    }

    @RequestMapping("listFile")
    @ResponseBody
    public List<Map<String, String>> listFile(String path) throws Exception {
        return hdfsUtils.listFile(path);
    }
    @RequestMapping("rename")
    @ResponseBody
    public boolean rename(String oldPath,String newPath) throws Exception{
        return hdfsUtils.renameFile(oldPath,newPath);
    }
    @RequestMapping("delete")
    @ResponseBody
    public boolean delete(String path) throws Exception{
        return hdfsUtils.deleteFile(path);
    }
    @RequestMapping("getFileBlockLocations")
    @ResponseBody
    public Object getFileBlockLocations(String path)throws Exception{
        BlockLocation[] blockLocations =hdfsUtils.getFileBlockLocations(path);
        return blockLocations;
    }


    @RequestMapping("copyFile")
    @ResponseBody
    public String copyFile(String source,String target) throws Exception{
        hdfsUtils.copyFile(source,target);
        return "success";
    }


}
